<template>
  <div class="search-box">
    <!-- 顶部搜索 -->
    <!-- 在 van-search 外层增加 form 标签，且 action 不为空，即可在 iOS 输入法中显示搜索按钮 -->
    <!-- 路由导航 -->
    <!-- 声明式: router-link 通过标签的方式进行跳转 -->
    <!-- 编程式: 通过js进行跳转 this.$router.go() push() -->
    <form class="header-serarch" action="/">
      <van-search
        v-model="searchText"
        show-action
        placeholder="请输入搜索关键词"
        background="#3296FA"
        @search="onSearch"
        @cancel="$router.go(-1)"
        @focus="isShowSearchResults = false"
      />
    </form>

    <!-- 搜索结果 -->
    <SearchResults :value="searchText" v-if="isShowSearchResults" />
    <!-- 搜索历史 -->
    <SearchHistory :history="history" v-else-if="!searchText" @search="onSearch" @clearHistory="history = []" />
    <!-- 搜索建议 -->
    <SearchSuggestion @search="onSearch" :value="searchText" v-else />
  </div>
</template>

<script>
import SearchHistory from './components/search-history.vue'
import SearchSuggestion from './components/search-suggestion.vue'
import SearchResults from './components/search-results.vue'
import { setItem, getItem } from '@/utils/storage.js'
// 黑马头条的搜索历史的key
const HMTT_HISTORY = 'hmtt_history'
export default {
  name: 'search',
  data () {
    return {
      searchText: '',
      isShowSearchResults: false, // 是否显示搜索结果
      history: getItem(HMTT_HISTORY) || []
    }
  },

  components: {
    SearchHistory,
    SearchSuggestion,
    SearchResults
  },

  created () {

  },

  watch: {
    history (nVal) {
      setItem(HMTT_HISTORY, nVal)
    }
  },

  methods: {
    // 触发搜索
    // 移动端: 点击搜索按键
    // pc: 敲回车
    onSearch (val) {
      // console.log(val)
      // 存储搜索历史
      // const index = this.history.findIndex(item => item === val)
      // if (index !== -1) {
      //   this.history.splice(index, 1)
      // }
      this.history.unshift(val)
      this.history = [...new Set(this.history)]
      // 同步输入框
      this.searchText = val
      // 显示搜索结果
      this.isShowSearchResults = true
    }
    // onCancel () {
    //   this.$router.go(-1)
    // }
  }
}
</script>

<style scoped lang='less'>
.search-box {
  .header-serarch {
    position: sticky;
    top: 0px;
    z-index: 2;
  }
  .van-search__action {
    color: #fff;
  }
}
</style>
